var Config = require("../config");
var KOC = require("koc.common.utils");
var https = require('https');
var iconv = require('iconv-lite');
module.exports = {
    /////////////////////////////////////////
    //获取UID
    /////////////////////////////////////////
    Send: function (receiptData, User_ID, callback) {
        var receiptEnvelopeStr = JSON.stringify({'receipt-data': receiptData});
        var hostname = '';
        var urls = '';
        if (Config.Common.Virtual_Path.Main == 'http://www.x.xiutv.com/') {
            hostname = 'sandbox.itunes.apple.com';
            urls = 'https://sandbox.itunes.apple.com/verifyReceipt';
        } else {
            if (User_ID == 5374 || User_ID == 6126) {
                hostname = 'sandbox.itunes.apple.com';
                urls = 'https://sandbox.itunes.apple.com/verifyReceipt';
            } else {
                hostname = 'buy.itunes.apple.com';
                urls = 'https://buy.itunes.apple.com/verifyReceipt';
            }
        }
        var options = {
            hostname: hostname,
            path: '/verifyReceipt',
            url: urls,
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Content-Length': receiptEnvelopeStr.length
            },
            body: receiptEnvelopeStr
        };
        KOC.Request(options, function (err, response, result) {
            if (err) {
                callback(KOC.ReturnValue.New({
                    hasError: true,
                    message: err.message
                }));
                return;
            }
            try {
                result = JSON.parse(result);
            } catch (ex) {
                result = null;
            }
            if (!result) {
                callback(KOC.ReturnValue.New({
                    hasError: true,
                    errorCode: 3,
                    message: '没有返回参数'
                }));
                return;
            }

            if (result.status != 0) {
                callback(KOC.ReturnValue.New({
                    hasError: true,
                    errorCode: result.status,
                    message: '返回参数出错'
                }));
                return;
            }
            callback(KOC.ReturnValue.New({
                message: "",
                returnObject: {
                    Status: result.status,
                    Quantity: result.receipt.in_app[0].quantity,
                    Pay_Money: result.receipt.in_app[0].product_id.replace('com.tiantian.quanminxiu_recharge_', '').replace('CNY', '').trim(),
                    Pay_TransNumber: result.receipt.in_app[0].transaction_id
                }
            }));
        });
    }
};